package com.example.app.components.MyPlaceSelected

import android.os.Bundle
import android.util.Log
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.ViewModel
import androidx.lifecycle.compose.LocalLifecycleOwner
import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.maps.AMap
import com.amap.api.maps.AMap.OnMapReadyListener
import com.amap.api.maps.MapView
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.Marker
import com.amap.api.services.core.PoiItemV2
import com.amap.apis.utils.core.api.AMapUtilCoreApi
import com.example.app.R
import com.example.app.components.MyButton.MyFillSmallButton
import com.example.app.components.MyIcon.MyNavigationIcon
import com.example.app.components.MySurface.MySurface
import com.example.app.components.MyTopBar.MyTopBar
import com.example.app.myMapSelectedState
import com.example.app.ui.theme.listItemStartPadding
import com.google.accompanist.permissions.ExperimentalPermissionsApi

class MyMapSelectedState : ViewModel() {
    var mapOpenState = mutableStateOf(false)
    var showSubmit = mutableStateOf(false)
    var showPlaceBottomSheet = mutableStateOf(false)
}

data class MyMapSelectedSelectedData(
    var latLng: LatLng? = null,
    var title: String? = null
) {
    fun isEmpty(): Boolean {
        return latLng == null || title == null
    }
}
@OptIn(
    ExperimentalLayoutApi::class,
    ExperimentalPermissionsApi::class,
    ExperimentalMaterial3Api::class
)
@Composable
fun MyMapSelected(
    emitsFromMyMapSelected: (latLng: LatLng?, title: String?) -> Unit
) {
    var myMapSelectedSelectedData = MyMapSelectedSelectedData()
    var context = LocalContext.current
    //初始化协议，必须
    AMapUtilCoreApi.setCollectInfoEnable(true)
    AMapLocationClient.updatePrivacyShow(
        context,
        true,
        true
    )
    AMapLocationClient.updatePrivacyAgree(
        context,
        true
    )
    var aMapLocation: AMapLocation? = null
    var mapInstance: AMap? = null
    val mapView = MapView(context)
    mapView.apply {
        id = R.id.map
        getMapAsyn(object : OnMapReadyListener {
            override fun onMapReady(p0: AMap?) {
                mapInstance = p0
            }
        })
    }
    val locationOption = AMapLocationClientOption().apply {
        interval = 1000
    }
    var curMarker: Marker? = null
    var latLng: LatLng? = null
    var locationClient = AMapLocationClient(context)
    var _suggestionsList = mutableListOf<PoiItemV2>()

    locationClient.setLocationListener { loc ->
        aMapLocation = loc
        if (loc != null) {
            if (loc.errorCode == 0) {
                Log.d(
                    "easy",
                    "定位成功: ${loc.latitude}, ${loc.longitude}"
                )
                latLng = LatLng(
                    loc.latitude,
                    loc.longitude
                )
                if (mapInstance != null) {
                    getLatLngHandler(
                        props = {
                            it(
                                latLng!!,
                                locationClient,
                                mapInstance!!,
                                curMarker,
                                loc.aoiName
                            )
                        },
                        emitsFromGetLatLngHandler = {
                            curMarker = it
                        },
                        markerClickHandler = {
                            if (it == curMarker) {
                                //  textFieldValue = TextFieldValue(loc.aoiName)
                                return@getLatLngHandler true
                            } else {
                                return@getLatLngHandler false
                            }
                        },
                    )

                    searchPlaceHandler(
                        text = loc.aoiName,
                        latLng = latLng,
                        context = context,
                        suggestionsList = _suggestionsList,
                        emitFromSearchPlaceHandler = { suggestionsList ->
                            _suggestionsList.clear()
                            _suggestionsList.addAll(suggestionsList)
                        }
                    )
                }
            } else {
                Log.e(
                    "easy",
                    "定位失败: ${loc.errorInfo} (错误码: ${loc.errorCode})"
                )
            }
        }
    }
    var lifecycleOwner = LocalLifecycleOwner.current
    var lifecycle = lifecycleOwner.lifecycle
    //建一个生命周期监听
    var observer = LifecycleEventObserver({ source, event ->
        when (event) {
            Lifecycle.Event.ON_START -> {
                locationClient.startLocation()
                locationClient.setLocationOption(locationOption)
                mapView.onCreate(Bundle())
            }

            Lifecycle.Event.ON_CREATE -> {
            }

            Lifecycle.Event.ON_RESUME -> {
            }

            Lifecycle.Event.ON_PAUSE -> {
            }

            Lifecycle.Event.ON_DESTROY -> {
            }

            Lifecycle.Event.ON_STOP -> {
            }

            else -> {
            }
        }
    })
    DisposableEffect(Unit) {
        //添加监听
        lifecycle.addObserver(observer)
        onDispose {
            locationClient.stopLocation()
            locationClient.onDestroy()
            mapView.onDestroy()
            //移除监听
            lifecycle.removeObserver(observer)
        }
    }



    MySurface(
        modifier = Modifier.fillMaxSize()
    ) {
        var density = LocalDensity.current

        Column(
            modifier = Modifier
                .fillMaxSize(),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.SpaceBetween
        ) {
            AndroidView(
                modifier = Modifier.weight(1f),
                factory = { mapView },
                update = {
                }
            )

            MapSearchSuggestsView(

                //将父组件的变量传入，具体如何实现函数参数里面的函数，让子组件去实现，父组件只是负责传递变量
                props = {
                    it(
                        mapInstance,
                        latLng,
                        aMapLocation,
                        _suggestionsList
                    )
                },
                //从子组件接收变量
                emitsFromMapSearchSuggestsView = { latLng: LatLng?, title: String? ->
                    if (latLng != null && title != null) {
                        getLatLngHandler(
                            props = {
                                it(
                                    latLng,
                                    locationClient,
                                    mapInstance!!,
                                    curMarker,
                                    title
                                )
                            },
                            emitsFromGetLatLngHandler = {
                                curMarker = it
                            },
                            markerClickHandler = {
                                true
                            }
                        )
                        myMapSelectedSelectedData.latLng = latLng
                        myMapSelectedSelectedData.title = title
                        myMapSelectedState.showSubmit.value = true
                    } else {
                        myMapSelectedSelectedData.latLng = null
                        myMapSelectedSelectedData.title = null
                        myMapSelectedState.showSubmit.value = false
                    }
                }
            )
        }


        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(TopAppBarDefaults.TopAppBarExpandedHeight)
        ) {
            MyTopBar(
                colModifier = Modifier
                    .background(Color.Black.copy(alpha = .25f))
                    .padding(PaddingValues(listItemStartPadding / 2,
                        0.dp))
                    .fillMaxWidth(),
                colors = TopAppBarDefaults.centerAlignedTopAppBarColors(
                    containerColor = Color.Transparent,
                ),
                title = {
                },
                navigationIcon = {
                    MyNavigationIcon(
                        onClick = {
                            myMapSelectedState.mapOpenState.value = false
                        },
                        tint = MaterialTheme.colorScheme.surface
                    )
                },
                actions = {
                    if (myMapSelectedState.showSubmit.value) {
                        //提交按钮
                        MyFillSmallButton(
                            onClick = {
                                if (!myMapSelectedSelectedData.isEmpty()) {
                                    emitsFromMyMapSelected(
                                        myMapSelectedSelectedData.latLng,
                                        myMapSelectedSelectedData.title
                                    )
                                    myMapSelectedState.mapOpenState.value = false
                                    myMapSelectedState.showSubmit.value = false
                                }
                            },
                            text = "提交"
                        )
                    }
                }
            )
        }
    }
}